import React, { useState } from "react";
import { useDispatch,useSelector } from "react-redux";
//import { addNewPost } from "./postsSlice";
import { selectAllUsers } from "./../users/usersSlice";
//import { nanoid } from "@reduxjs/toolkit";
import { useAddNewPostMutation } from '../api/apiSlice'


const AddPostForm = () => {
  const [title, setTitle] = useState("");
  const [content, setContent] = useState("");
  const [userId, setUserId] = useState("");
  
  const [addRequestStatus, setAddRequestStatus] = useState("idle");
  
  //const users = useSelector((state) => state.users);
  const users = useSelector(selectAllUsers);

  const dispatch = useDispatch();

  const [addNewPost,{ isLoading}] = useAddNewPostMutation();

  const onTitleChanged = (e) => setTitle(e.target.value);
  const onContentChanged = (e) => setContent(e.target.value);
  const onAuthorChanged = (e) => setUserId(e.target.value);



  // const onSavePostClicked = () => {
  //   if(title && content) {
  //       dispatch(
  //           // postAdded({
  //           //     //id: nanoid(),
  //           //     title,
  //           //     content,
  //           // })

  //           postAdded(title,content,userId)
  //       );
  //       setTitle("");
  //       setContent("");
  //   }
  // }

  const onSavePostClicked = async () => {
    if (canSave) {
      try {
        setAddRequestStatus("pending");
        await dispatch(addNewPost({ title, content, user: userId })).unwrap();
        setTitle("");
        setContent("");
        setUserId("");
      } catch (err) {
        console.error("Failed to save the post: ", err);
      } finally {
        setAddRequestStatus("idle");
      }
    }
  };

  const usersOptions = users?.map((user) => (
    <option key={user.id} value={user.id}>
      {user.name}
    </option>
  ));

  const canSave =[title, content, userId].every(Boolean) && addRequestStatus === "idle";

  
  return (
    <section>
      <h2>添加新文章</h2>
      <form>
        <div>
          <label htmlFor="postAuthor">Author:</label>
          <select id="postAuthor" value={userId} onChange={onAuthorChanged}>
            <option value=""></option>
            {usersOptions}
          </select>
        </div>
        <div>
            <label htmlFor="postTitle">文章标题:</label>
            <input
                type="text"
                id="postTitle"
                name="postTitle"
                value={title}
                onChange={onTitleChanged}
            />
        </div>
        <div>
            <label htmlFor="postContent">内容：</label>
            <textarea
                id="postContent"
                name="postContent"
                value={content}
                onChange={onContentChanged}
            />
        </div>
        <button type="button" onClick={onSavePostClicked} disabled={!canSave}>保存文章</button>
      </form>
    </section>
  );
};

export default AddPostForm;